// 浏览器指纹保护脚本
(function() {
  'use strict';

  const fingerprintConfig = {
    userAgent: null,
    screen: null,
    timezone: null,
    language: null,
    webgl: true,
    canvas: true,
    audioContext: true,
    webrtc: true
  };

  // 检查扩展上下文是否有效
  function isExtensionContextValid() {
    try {
      return !!(chrome.runtime && chrome.runtime.id);
    } catch (error) {
      return false;
    }
  }

  // 获取会话配置
  async function getSessionConfig() {
    try {
      if (!isExtensionContextValid()) {
        console.warn('扩展上下文无效，使用默认指纹保护配置');
        return;
      }

      const response = await chrome.runtime.sendMessage({
        action: 'getSessionFingerprint'
      });
      if (response && response.success) {
        Object.assign(fingerprintConfig, response.config);
      }
    } catch (error) {
      if (error.message && error.message.includes('Extension context invalidated')) {
        console.warn('扩展上下文已失效，使用默认指纹保护配置');
      } else {
        console.warn('获取会话指纹配置失败:', error);
      }
    }
  }

  // User Agent 保护
  function protectUserAgent() {
    if (fingerprintConfig.userAgent) {
      Object.defineProperty(navigator, 'userAgent', {
        get: () => fingerprintConfig.userAgent,
        configurable: false
      });
    }
  }

  // Screen 信息保护
  function protectScreen() {
    if (fingerprintConfig.screen) {
      const { width, height, colorDepth, pixelDepth } = fingerprintConfig.screen;
      
      Object.defineProperties(screen, {
        width: { get: () => width, configurable: false },
        height: { get: () => height, configurable: false },
        availWidth: { get: () => width, configurable: false },
        availHeight: { get: () => height - 40, configurable: false }, // 减去任务栏高度
        colorDepth: { get: () => colorDepth, configurable: false },
        pixelDepth: { get: () => pixelDepth, configurable: false }
      });
    }
  }

  // 时区保护
  function protectTimezone() {
    if (fingerprintConfig.timezone) {
      const originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
      Date.prototype.getTimezoneOffset = function() {
        return fingerprintConfig.timezone;
      };
    }
  }

  // 语言保护
  function protectLanguage() {
    if (fingerprintConfig.language) {
      Object.defineProperties(navigator, {
        language: { get: () => fingerprintConfig.language, configurable: false },
        languages: { get: () => [fingerprintConfig.language], configurable: false }
      });
    }
  }

  // Canvas 指纹保护
  function protectCanvas() {
    if (!fingerprintConfig.canvas) return;

    const originalToDataURL = HTMLCanvasElement.prototype.toDataURL;
    const originalGetImageData = CanvasRenderingContext2D.prototype.getImageData;

    HTMLCanvasElement.prototype.toDataURL = function(type, encoderOptions) {
      const result = originalToDataURL.call(this, type, encoderOptions);
      // 添加随机噪声
      return addCanvasNoise(result);
    };

    CanvasRenderingContext2D.prototype.getImageData = function(sx, sy, sw, sh) {
      const result = originalGetImageData.call(this, sx, sy, sw, sh);
      // 添加微小的随机变化
      addImageDataNoise(result);
      return result;
    };
  }

  // WebGL 指纹保护
  function protectWebGL() {
    if (!fingerprintConfig.webgl) return;

    const originalGetParameter = WebGLRenderingContext.prototype.getParameter;
    const originalGetExtension = WebGLRenderingContext.prototype.getExtension;

    WebGLRenderingContext.prototype.getParameter = function(parameter) {
      // 修改关键的WebGL参数
      switch (parameter) {
        case this.VENDOR:
          return 'Intel Inc.';
        case this.RENDERER:
          return 'Intel Iris OpenGL Engine';
        case this.VERSION:
          return 'WebGL 1.0 (OpenGL ES 2.0 Chromium)';
        case this.SHADING_LANGUAGE_VERSION:
          return 'WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)';
        default:
          return originalGetParameter.call(this, parameter);
      }
    };
  }

  // AudioContext 指纹保护
  function protectAudioContext() {
    if (!fingerprintConfig.audioContext) return;

    const AudioContext = window.AudioContext || window.webkitAudioContext;
    if (!AudioContext) return;

    const originalCreateAnalyser = AudioContext.prototype.createAnalyser;
    AudioContext.prototype.createAnalyser = function() {
      const analyser = originalCreateAnalyser.call(this);
      const originalGetFloatFrequencyData = analyser.getFloatFrequencyData;
      
      analyser.getFloatFrequencyData = function(array) {
        originalGetFloatFrequencyData.call(this, array);
        // 添加微小的随机噪声
        for (let i = 0; i < array.length; i++) {
          array[i] += (Math.random() - 0.5) * 0.0001;
        }
      };
      
      return analyser;
    };
  }

  // WebRTC 保护
  function protectWebRTC() {
    if (!fingerprintConfig.webrtc) return;

    // 阻止WebRTC泄露真实IP
    const originalRTCPeerConnection = window.RTCPeerConnection;
    if (originalRTCPeerConnection) {
      window.RTCPeerConnection = function(config, constraints) {
        if (config && config.iceServers) {
          config.iceServers = [];
        }
        return new originalRTCPeerConnection(config, constraints);
      };
    }
  }

  // 添加Canvas噪声
  function addCanvasNoise(dataURL) {
    // 简单的字符串修改来添加噪声
    const chars = dataURL.split('');
    const randomIndex = Math.floor(Math.random() * (chars.length - 10)) + 10;
    const randomChar = String.fromCharCode(Math.floor(Math.random() * 26) + 97);
    chars[randomIndex] = randomChar;
    return chars.join('');
  }

  // 添加ImageData噪声
  function addImageDataNoise(imageData) {
    const data = imageData.data;
    for (let i = 0; i < data.length; i += 4) {
      // 对RGB值添加微小的随机变化
      if (Math.random() < 0.01) { // 1%的像素
        data[i] = Math.min(255, Math.max(0, data[i] + (Math.random() - 0.5) * 2));
        data[i + 1] = Math.min(255, Math.max(0, data[i + 1] + (Math.random() - 0.5) * 2));
        data[i + 2] = Math.min(255, Math.max(0, data[i + 2] + (Math.random() - 0.5) * 2));
      }
    }
  }

  // 初始化指纹保护
  async function initFingerprintProtection() {
    await getSessionConfig();
    
    protectUserAgent();
    protectScreen();
    protectTimezone();
    protectLanguage();
    protectCanvas();
    protectWebGL();
    protectAudioContext();
    protectWebRTC();
    
    console.log('指纹保护已初始化');
  }

  // 立即执行保护
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initFingerprintProtection);
  } else {
    initFingerprintProtection();
  }

})(); 